from django.conf import settings
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from apps.accounts.models import User
from apps.chefs.models import Chef
from apps.orders.models import Order

class Review(models.Model):
    RATING_CHOICES = [
        (1, '★☆☆☆☆ 不满意'),
        (2, '★★☆☆☆ 一般'),
        (3, '★★★☆☆ 满意'),
        (4, '★★★★☆ 很满意'),
        (5, '★★★★★ 非常棒')
    ]

    order = models.OneToOneField(
        Order,
        on_delete=models.CASCADE,
        related_name='review',
        unique=True  # 确保一个订单只能有一个评价
    )
    customer = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='reviews_given'
    )
    chef = models.ForeignKey(
        Chef,
        on_delete=models.CASCADE,
        related_name='reviews_received'
    )
    
    # 评价维度
    food_quality = models.PositiveSmallIntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(5)],
        verbose_name='菜品质量'
    )
    service = models.PositiveSmallIntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(5)],
        verbose_name='服务质量'
    )
    cleanliness = models.PositiveSmallIntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(5)],
        verbose_name='卫生状况'
    )
    
    # 综合评分（自动计算）
    overall_rating = models.FloatField(editable=False)
    
    comment = models.TextField(max_length=500, blank=True)
    photos = models.ManyToManyField('ReviewPhoto', blank=True, related_name='review_photos')
    
    is_public = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']
        verbose_name = '评价'
        verbose_name_plural = '评价'
        constraints = [
            models.UniqueConstraint(
                fields=['order', 'customer', 'chef'],
                name='unique_review_per_order'
            )
        ]

    def save(self, *args, **kwargs):
        # 自动计算综合评分（加权平均）
        self.overall_rating = round((
            self.food_quality * 0.5 +
            self.service * 0.3 +
            self.cleanliness * 0.2
        ), 1)
        super().save(*args, **kwargs)
        
        # 更新厨师平均评分
        self.update_chef_rating()

    def update_chef_rating(self):
        reviews = Review.objects.filter(chef=self.chef)
        total_reviews = reviews.count()
        
        avg_food = reviews.aggregate(models.Avg('food_quality'))['food_quality__avg']
        avg_service = reviews.aggregate(models.Avg('service'))['service__avg']
        avg_clean = reviews.aggregate(models.Avg('cleanliness'))['cleanliness__avg']
        
        self.chef.rating = round((
            avg_food * 0.5 +
            avg_service * 0.3 +
            avg_clean * 0.2
        ), 1)
        self.chef.review_count = total_reviews
        self.chef.save()

    @property
    def image_urls(self):
        return [photo.image.url for photo in self.photos.all()]
    
    class Meta:
        # 添加索引
        indexes = [
            models.Index(fields=['chef', 'is_public']),
            models.Index(fields=['customer', 'created_at']),
        ]

class ReviewPhoto(models.Model):
    review = models.ForeignKey(
        Review,
        on_delete=models.CASCADE,
        related_name='review_photos'
    )
    image = models.ImageField(
        upload_to='review_photos/%Y/%m/',
        verbose_name='评价图片'
    )
    uploaded_at = models.DateTimeField(auto_now_add=True)

    is_approved = models.BooleanField(
        default=False,
        verbose_name='审核通过'
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        verbose_name='审核人'
    )
    approved_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    

    class Meta:
        verbose_name = '评价图片'
        verbose_name_plural = '评价图片'